<template>
  <div style=" " class="common-dialog-form">
    <span v-for="(wrapitem, index) in list" :style="` display: flex; width: 100%; margin-top: ${index === 0 ? '8px' : '16px'}; `">
      <span v-for="(item, index2) in wrapitem" :key="index2"
            :style="`padding-right: 22px;   position: relative;  width: ${item.rowWidth || width}; flex-wrap: wrap; ` ">
        <span v-if="item.type === 'input'" :style="`display: flex; width: 100%; `">
          <span v-if="item.required" class="text-center text-star">*</span>
          <span class="text-center "
                :style="`color: #0e0e0e; word-break: keep-all; font-size: 14px; width: ${item.width};`">
            {{ item.text }}</span>
          <el-input :style="`width: ${item.inputWidth}; flex: 1;`" clearable v-model="item.value"
                    :placeholder="item.placeholder || '请输入内容'"></el-input>
        </span>
        <div class="common-dialog-form-title" :style="`display: flex; width: 100%; `"
             v-else-if="item.type === 'largeTitle'">
          {{ item.title }}
        </div>
        <span v-else-if="item.type === 'inputnumber'" style="display: flex;">
          <span class="text-center" :style="`font-size: 14px; color: #000; width: ${item.width};`">{{ item.text }}</span>
<!--          <el-input :min="0" :style="`width: ${item.inputWidth || '150px'};`" type="number"-->
<!--                    v-model.number="item.value" :placeholder="item.placeholder || '￥0.00'"-->
<!--                    -->
<!--                    :precision="2">-->
<!--              <template slot="append" v-if="item.appendText">{{ item.appendText }} </template>-->
<!--          </el-input>-->
          <el-input-number :size="item.size || 'small'" @change="item.changeEvent"
                           :style="`${item.inputWidth ? `width: calc(${item.inputWidth} - ${item.width})` : '150px'};`" :placeholder="item.placeholder || '￥0.00'"
                           @blur="() => {
                            if(item.keepDecimal) {
                              item.value = keepTwoDecimalFull(item.value)
                            }
                           }"
                           controls-position="right"
                           v-model="item.value" :step="1" :min="0"></el-input-number>
        </span>
        <span v-else-if="item.type === 'button'" :style="`display: flex;   `">
          <el-button type="primary" @click="item.event" :icon="item.buttonIcon">{{ item.buttonText }}</el-button>
        </span>
        <span v-else-if="item.type === 'selectTree'" :style="`display: flex;    `">
          <span v-if="item.required" class="text-center text-star">*</span>
          <span class="text-center"
                :style="`display: flex; word-break: keep-all; width: ${item.width}  ;    color: #0e0e0e; `">
            {{ item.text }}
          </span>
          <select-tree @selectTreeGetCurrentNode="selectTreeGetCurrentNode" :item="item"/>
        </span>
        <span v-else-if="item.type === 'selectTreeCustomer'" :style="`display: flex;    `">
          <span v-if="item.required" class="text-center text-star">*</span>
          <span class="text-center"
                :style="`display: flex; word-break: keep-all; width: ${item.width}  ;    color: #0e0e0e; `">
            {{ item.text }}
          </span>
          <customer-category-tree @selectTreeGetCurrentNode="selectTreeGetCurrentNode" :item="item"/>
        </span>
        <span v-else-if="item.type === 'selectTreeSupplier'" :style="`display: flex;    `">
          <span v-if="item.required" class="text-center text-star">*</span>
          <span class="text-center"
                :style="`display: flex; word-break: keep-all; width: ${item.width}  ;    color: #0e0e0e; `">
            {{ item.text }}
          </span>
          <supplier-category-tree @selectTreeGetCurrentNode="selectTreeGetCurrentNode" :item="item"/>
        </span>
        <span v-else-if="item.type === 'selectAllowCreate'" :style="`display: flex;    `">
          <span v-if="item.required" class="text-center text-star">*</span>
          <span class="text-center"
                :style="`display: flex; word-break: keep-all; width: ${item.width}  ;    color: #0e0e0e; `">
            {{ item.text }}
          </span>
           <el-select v-model="item.value" style="flex: 1;"
                      filterable allow-create :ref="item.ref"
                      default-first-option placeholder="请选择">
              <el-option v-for="item in item.options"
                         :key="item.value" :label="item.label"
                         :value="item.value">
                  <div>{{ item.label }}</div>
                  <div style="  color: #8492a6; font-size: 13px">{{ item.explain }}</div>
              </el-option>
           </el-select>
        </span>
        <span v-else-if="item.type === 'unitSelect'" :style="`display: flex;    `">
          <span v-if="item.required" class="text-center text-star">*</span>
          <span class="text-center"
                :style="`display: flex; word-break: keep-all; width: ${item.width}  ;    color: #0e0e0e; `">
            {{ item.text }}
          </span>
          <unit-select
              :style="` flex: 1;`"
              :new-unit="true" @setValue="(v) => item.value = v" :value="item.value" />
        </span>
        <span v-else-if="item.type === 'shopSelect'" :style="`display: flex;    `">
          <span v-if="item.required" class="text-center text-star">*</span>
          <span class="text-center"
                :style="`display: flex; word-break: keep-all; width: ${item.width}  ;    color: #0e0e0e; `">
            {{ item.text }}
          </span>
          <shop-select
              :style="` flex: 1;`"
              :new-unit="true" @setValue="(v) => item.value = v" :value="item.value" />
        </span>
        <span v-else-if="item.type === 'textarea'" :style="`display: flex; width: 100%;   `">
          <span v-if="item.required" class="text-center text-star">*</span>
          <span class="text-center"
                :style="`color: #0e0e0e; word-break: keep-all; font-size: 14px; width: ${item.width};`">
            {{ item.text }}</span>
          <el-input type="textarea" :style="`width: ${item.inputWidth}; flex: 1;`" clearable v-model="item.value"
                    :placeholder="item.placeholder || '请输入内容'"></el-input>
        </span>
        <span v-else-if="item.type === 'uploadPic'" :style="`display: flex;   `">
          <span v-if="item.required" class="text-center text-star">*</span>
          <span class="text-center"
                :style="`color: #0e0e0e; word-break: keep-all; font-size: 14px; width: ${item.width};`">
            {{ item.text }}
          </span>
          <el-upload :style="`width: ${item.uploadWidth};`"
                     class="upload-pic"
                     :action="uploadApi"
                     :on-preview="(file) => handlePreview(file, item)"
                     :on-success="(res, file) => handleSuccess(res, file, item)"
                     accept="image/gif,image/jpeg,image/jpg,image/png,image/svg"
                     :on-remove="(file, fileList) => handleRemove(file, fileList, item)"
                     :file-list="item.value" list-type="picture-card">
            <i class="el-icon-plus" type="primary"></i>
          </el-upload>

           <el-dialog append-to-body :visible.sync="item.dialogVisible">
              <img width="100%" :src="item.dialogImageUrl" alt="">
            </el-dialog>
        </span>
        <span v-else-if="item.type === 'checkbox'" :style="`display: flex;   `">
          <span v-if="item.required" class="text-center text-star">*</span>
          <span class="text-center"
                :style="`color: #0e0e0e; word-break: keep-all; font-size: 14px; width: ${item.width};`">
          </span>
          <el-checkbox v-model="item.value">{{ item.text }}</el-checkbox>
        </span>
        <span v-else-if="item.type === 'product-table'" :style="`display: flex;   `">
          <span v-if="item.required" class="text-center text-star">*</span>
          <span class="text-center"
                :style="`color: #0e0e0e; word-break: keep-all; font-size: 14px; width: ${item.width};`">
            {{ item.text }}
          </span>

          <div style="flex: 1;">
            <div>
              <common-operation-form style="  flex: 1; margin-bottom: 6px;" :marginTop="'0px'"
                                     :list="item.productCommonList"/>
            </div>
            <el-table :data="item.data" border style="flex: 1;">
              <template v-for="(item2, index) in item.header">
                <el-table-column :prop="item2.prop"
                                 :width="item2.width || 'auto'" :align="`center`" :key="Math.random()"
                                 :label="item2.label">
                <template slot-scope="scope">
                  <span style=" " v-if="item2.prop === 'operate'">
                     <el-tooltip content="删除" slot="reference" placement="top">
                        <el-button size="mini" @click="item.del(scope.$index, scope.row, item.data)" type="danger"
                                   icon="el-icon-delete"
                                   circle></el-button>
                      </el-tooltip>
                  </span>
                  <span v-else-if="item2.prop === 'warehouseName'" style=" ">{{ scope.row[item2.prop] }}</span>
                  <el-input v-else-if="item2.prop === 'initialPrice'" :min="0"
                            @blur="calculateInitialValue(scope.row, scope, item.data, 'initialPrice')"
                            type="number" v-model.number="scope.row[item2.prop]"></el-input>
                  <el-input v-else-if="item2.prop === 'initialInventory'" :min="0" :precision="2"
                            @blur="calculateInitialValue(scope.row, scope, item.data, 'initialInventory')"
                            type="number" v-model.number="scope.row[item2.prop]"></el-input>
                  <el-input v-else-if="item2.prop === 'initialTotalPrice'" :min="0" :precision="2"
                            @blur="calculateInitialValue(scope.row, scope, item.data, 'initialTotalPrice')"
                            type="number" v-model.number="scope.row[item2.prop]"></el-input>
                </template>
              </el-table-column>
              </template>
            </el-table>
          </div>
        </span>
        <span v-else-if="item.type === 'radio'" :style="`display: flex;   `">
          <span v-if="item.required" class="text-center text-star">*</span>
          <span class="text-center"
                :style="`color: #0e0e0e; word-break: keep-all; font-size: 14px; width: ${item.width};`">
            {{ item.text }}
          </span>
          <el-radio v-for="(item2, index2) in item.list" v-model="item.value"
                    :label="item2.value">{{ item2.label }}</el-radio>
        </span>
        <span v-else-if="item.type === 'businessType'" :style="`display: flex; width: 100%; `">
          <div :style="`width: ${item.width}; margin-top: 6px;`">
            <span v-if="item.required" class="text-center text-star">*</span>
            <span class="text-center "
                  :style="`color: #0e0e0e; word-break: keep-all; font-size: 14px; width: ${item.width};`">
              {{ item.text }}
            </span>
          </div>
          <span style="display: flex; flex-wrap: wrap; ">
            <el-button size="mini" v-for="(item2, index) in item.options" @click="item.clickEvent(index)" :class="`${item.value === index ? 'businessTypeChoose' : ''}`"  plain style="width: 80px; margin-left: 0; margin-right: 8px; margin-bottom: 8px;">{{item2.name}}</el-button>
          </span>
        </span>
        <span v-else-if="item.type === 'selectPermission'"  :style="`display: flex;    `">
          <span v-if="item.required" class="text-center text-star">*</span>
          <span class="text-center"
                :style="`display: flex; word-break: keep-all; width: ${item.width}  ;    color: #0e0e0e; `">
            {{ item.text }}
          </span>
           <el-select v-model="item.value" style="flex: 1;" popper-class="selectPermission"
                      filterable  :ref="item.ref"
                      default-first-option placeholder="请选择">
              <el-option v-for="item in item.options"
                         :key="item.value" :label="item.label"
                         :value="item.value">
                  <div style="line-height: 24px; ">{{ item.label }}</div>
                  <div style="  color: #8492a6; line-height: 16px; font-size: 13px">{{ item.explain }}</div>
              </el-option>
           </el-select>
        </span>
        <span v-else :style="`display: flex; width: ${width} `"></span>
      </span>
    </span>
  </div>
</template>

<script>
import SelectTree from "@/components/SelectTree/index.vue";
import CustomerCategoryTree from "@/components/SelectTree/customerCategoryTree.vue";
import SupplierCategoryTree from "@/components/SelectTree/supplierCategoryTree.vue";
import {isValidAmount} from "@/utils";
import CommonOperationForm from "@/components/CommonOperationForm/index.vue";
import UnitSelect from "@/components/Unit/UnitSelect.vue";
import ShopSelect from "@/components/Shop/ShopSelect.vue";

export default {
  props: ["list", "col"],
  components: {CommonOperationForm, UnitSelect, ShopSelect, SelectTree, CustomerCategoryTree, SupplierCategoryTree,},
  data() {
    return {
      width: '',
    }
  },
  mounted() {
    this.width = 100 / this.col + '%';
  },
  methods: {
    event22() {
      console.log(176)
    },
    handlePreview(file, item) {
      console.log(item);
      item.dialogImageUrl = file.url;
      item.dialogVisible = true;
    },
    handleRemove(file, fileList, item) {
      item.value = fileList;
    },
    keepTwoDecimalFull(num, decimal = 2) {
      num = num.toString()
      let index = num.indexOf('.')
      if (index !== -1) {
        num = num.substring(0, decimal + index + 1)
      } else {
        num = num.substring(0)
      }
      return parseFloat(num).toFixed(decimal)
    },
    handleSuccess(res, file, item) {
      file['name'] = res.file;
      item.value.push(file);
    },
    requiredEmpty() {
      function checkValue(required, value, item) {
        if (required) {
          if (value === null)
            return item;

          if (typeof value === 'string' && value.trim() === '')
            return item;
        }
        return null;
      }


      for (const inputSet of this.list) {
        for (const inputItem of inputSet) {
          let item = checkValue(inputItem.required, inputItem.value, inputItem);
          if (item)
            return item;

          // 检查 输入的金额是否准确
          if (inputItem.type === 'inputnumber') {
            if (!isValidAmount(inputItem.value + '')) {
              return {
                requiredMessage: inputItem.text + '请输入正确的金额',
              }
            }
          }
        }
      }


      return null;
    },
    selectTreeGetCurrentNode(v, v2) {
      v.value = v2['id'];
      v.node = v2['label'];
    },
    calculateInitialValue(item, scope, tableData, inputField) {
      function isNotANumberOrEmpty(value) {
        // 先检查是否为空
        if (value === "" || value === null || value === undefined) {
          return true;
        }

        // 使用isNaN来判断是否不是数字
        return isNaN(value);
      }

      let index = scope.$index;
      let inventory = parseInt(item.initialInventory);
      let price = parseFloat(item.initialPrice);
      let totalPrice = parseFloat(item.initialTotalPrice);

      if (inputField === 'initialInventory') {
        if (isNotANumberOrEmpty(inventory) && (!isNotANumberOrEmpty(price) || !isNotANumberOrEmpty(totalPrice))) {
          inventory = 0;
        }

        if (!isNotANumberOrEmpty(price)) { // 如果 期初成本价 不为空 则优先计算 总价，不然就计算期初成本价
          totalPrice = price * inventory;
        } else {
          price = totalPrice / inventory;
        }
      }
      if (inputField === 'initialPrice') {
        if (isNotANumberOrEmpty(price) && (!isNotANumberOrEmpty(inventory) || !isNotANumberOrEmpty(totalPrice))) {
          price = 0.00;
        }

        if (!isNotANumberOrEmpty(inventory)) { // 只能计算总价
          totalPrice = price * inventory;
        }
      }
      if (inputField === 'initialTotalPrice') {
        if (isNotANumberOrEmpty(totalPrice) && (!isNotANumberOrEmpty(inventory) || !isNotANumberOrEmpty(price))) {
          totalPrice = 0.00;
        }

        if (!isNotANumberOrEmpty(inventory)) {
          price = totalPrice / inventory;
        }
      }

      item.initialTotalPrice = this.keepTwoDecimalFull(totalPrice);
      item.initialPrice = this.keepTwoDecimalFull(price);
      item.initialInventory = inventory;

      this.$set(tableData, index, item);
    },
    getData() {
      let data = {};
      for (const inputSet of this.list) {
        for (const inputItem of inputSet) {
          if (inputItem['field'] === 'productPic') {
            let v = inputItem['value'];
            let arr = [];
            for (let i = 0; i < v.length; i++) {
              arr.push({
                name: v[i]['name']
              })
            }

            data[inputItem['field']] = arr;
          } else if (inputItem['field'] === 'productInitialInventory') {
            data[inputItem['field']] = inputItem['data'];
          } else {
            if (inputItem['field'] === 'productCategory') {
              data[inputItem['field'] + 'Label'] = inputItem['node'];
            }

            if (inputItem['field'] === 'customerCategory') {
              data[inputItem['field'] + 'Label'] = inputItem['node'];
            }

            if (inputItem['field'] === 'supplierCategory') {
              data[inputItem['field'] + 'Label'] = inputItem['node'];
            }

            data[inputItem['field']] = inputItem['value'];
          }
        }
      }

      return data;
    },
  }
}
</script>


<style lang="scss" scoped>
.dashboard {
  &-container {
    background: #fff;
    margin: 20px;
    box-shadow: 0px 0px 10px 0px rgba(45, 51, 65, 0.08);
    border-radius: 10px;
  }

  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}

.text-center {
  display: flex;
  align-content: center;
  align-items: center;
}

.common-dialog-form-title {
  font-weight: 900;
  font-size: 16px;
  color: #000;
  margin-top: 6px;
}

.text-star {
  position: absolute;
  top: 6px;
  left: -8px;
  color: red;
  font-size: 22px;
}

.common-dialog-form .el-divider--horizontal {
  margin: 8px 0;
}
</style>
